<template>
    <div class="house-card">
        <!-- 图片区域 -->
        <div class="image-wrapper clickable" @click="handleClick">
            <img :src="coverImageUrl" :alt="house.title" />
        </div>

        <!-- 房源信息 -->
        <div class="content">
            <!-- 标题 -->
            <h3 class="title clickable" @click="handleClick">{{ house.title }}</h3>
            
            <!-- 小区名称 -->
            <p class="community">{{ house.community }}</p>

            <!-- 房源属性 -->
            <div class="house-info">
                <div class="info-item">{{ house.bedroom }} 室</div>
                <div class="info-item">{{ house.bathroom }} 卫</div>
                <div class="info-item">{{ house.area }} m²</div>
            </div>

            <!-- 价格 -->
            <div class="price">
                <span class="amount">¥{{ formatPrice(house.price) }}</span>
            </div>

            <!-- 经纪人和操作按钮 -->
            <div class="bottom">
                <!-- 经纪人信息 -->
                <div class="agent">
                    <img
                        :src="house.agentAvatar ? getFullImageUrl(house.agentAvatar) : '/images/agent/avatar-default.png'"
                        :alt="house.agentName || '经纪人'"
                        class="agent-avatar"
                    />
                    <span class="agent-name">{{ house.agentName || '暂无经纪人' }}</span>
                </div>

                <!-- 操作按钮 -->
                <div class="actions">
                    <button class="action-btn" @click.stop="handleShare">
                        <svg-icon name="house/info/link" />
                    </button>
                    <button class="action-btn" @click.stop="handleCollect" v-if="showCollectButton">
                        <svg-icon :name="isCollected ? 'house/info/star-filled' : 'house/info/star'" class="collect-icon" :class="{ active: isCollected }" />
                    </button>
                    <button class="action-btn">
                        <svg-icon name="house/info/minimize" />
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import { addFavorite, removeFavorite, checkFavorite } from '@/api/favorite'
import { getFullImageUrl } from '@/utils/imageUrl'
import { ref, onMounted, computed } from 'vue'

const props = defineProps({
    house: {
        type: Object,
        required: true
    },
    showCollectButton: {
        type: Boolean,
        default: true
    }
})

const emit = defineEmits(['collect-change'])
const router = useRouter()
const userStore = useUserStore()
const loginStore = useLoginStore()

// 收藏状态
const isCollected = ref(false)

// 检查收藏状态
const checkCollectStatus = async () => {
    try {
        const houseId = props.house.houseId || props.house.id
        if (!houseId) {
            console.log('检查收藏状态: 房源ID无效')
            return
        }
        
        console.log('开始检查收藏状态, 房源ID:', houseId)
        const res = await checkFavorite(houseId)
        console.log('收藏状态检查响应:', res)
        
        if (res.code === 200) {
            // 适配不同的后端返回结构
            const collected = res.data?.collected || res.collected || false
            console.log('设置收藏状态为:', collected)
            isCollected.value = collected
        } else {
            console.warn('检查收藏状态接口返回非200状态:', res)
        }
    } catch (error) {
        console.error('检查收藏状态失败:', error.message, error.stack)
    }
}

// 处理收藏/取消收藏
const handleCollect = async (e) => {
    // 阻止事件冒泡，避免触发卡片点击
    e.stopPropagation()
    
    try {
        const houseId = props.house.houseId || props.house.id
        console.log('收藏操作 - 当前状态:', isCollected.value ? '已收藏' : '未收藏', '房源ID:', houseId)
        
        if (!houseId) {
            ElMessage.error('房源ID无效')
            return
        }
        
        // 先检查一次当前收藏状态，确保与后端同步
        try {
            console.log('操作前重新检查收藏状态')
            const checkRes = await checkFavorite(houseId)
            if (checkRes.code === 200) {
                const serverCollected = checkRes.data?.collected || checkRes.collected || false
                console.log('服务端收藏状态:', serverCollected, '本地状态:', isCollected.value)
                
                // 如果状态不同步，更新本地状态并提示用户
                if (serverCollected !== isCollected.value) {
                    console.warn('收藏状态不同步，更新本地状态')
                    isCollected.value = serverCollected
                    ElMessage.warning('收藏状态已更新，请重试')
                    return
                }
            }
        } catch (checkError) {
            console.error('重新检查收藏状态失败:', checkError)
            // 继续操作，不中断流程
        }
        
        if (isCollected.value) {
            // 取消收藏
            console.log('开始取消收藏:', houseId)
            const res = await removeFavorite(houseId)
            console.log('取消收藏响应:', res)
            
            if (res.code === 200) {
                ElMessage.success('取消收藏成功')
                isCollected.value = false
                // 将收藏状态变化通知父组件
                emit('collect-change', { 
                    houseId, 
                    collected: false
                })
            } else {
                ElMessage.error(res.msg || '取消收藏失败')
                // 操作失败，重新检查状态
                await checkCollectStatus()
            }
        } else {
            // 添加收藏
            console.log('开始添加收藏:', houseId)
            const res = await addFavorite(houseId)
            console.log('添加收藏响应:', res)
            
            if (res.code === 200) {
                ElMessage.success('收藏成功')
                isCollected.value = true
                // 将收藏状态变化通知父组件
                emit('collect-change', { 
                    houseId, 
                    collected: true
                })
            } else {
                ElMessage.error(res.msg || '收藏失败')
                // 操作失败，重新检查状态
                await checkCollectStatus()
            }
        }
    } catch (error) {
        console.error('操作收藏失败:', error.message, error.stack)
        ElMessage.error(`操作失败: ${error.message}`)
        // 发生错误，重新检查状态
        await checkCollectStatus()
    }
}

// 在组件初始化时检查收藏状态
onMounted(() => {
    checkCollectStatus()
})

// 处理点击事件
const handleClick = () => {
    router.push(`/house/${props.house.houseId}`)
}

// 处理分享
const handleShare = () => {
    // 复制链接到剪贴板
    const url = `${window.location.origin}/house/${props.house.houseId}`
    navigator.clipboard.writeText(url).then(() => {
        ElMessage.success('链接已复制到剪贴板')
    })
}

// 格式化价格，添加千位分隔符
const formatPrice = (price) => {
    return price ? price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') : ''
}

// 计算coverImageUrl
const coverImageUrl = computed(() => {
    // 如果有封面图，使用封面图
    if (props.house.coverImage) {
        return getFullImageUrl(props.house.coverImage);
    }
    
    // 如果有images数组且不为空，使用第一张图片
    if (props.house.images && props.house.images.length > 0) {
        const firstImage = props.house.images[0];
        if (typeof firstImage === 'string') {
            return getFullImageUrl(firstImage);
        } else if (firstImage.imageUrl) {
            return getFullImageUrl(firstImage.imageUrl);
        }
    }
    
    // 如果既没有封面图也没有其他图片，使用默认图片
    return '/images/house/default-house.jpg';
})
</script>

<style lang="scss" scoped>
.house-card {
    width: 420px;
    background: #FFFFFF;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 16px rgba(74, 96, 161, 0.08);
    transition: all 0.3s;

    &:hover {
        box-shadow: 0 8px 24px rgba(74, 96, 161, 0.12);
    }

    .image-wrapper {
        width: 100%;
        height: 280px;
        position: relative;
        overflow: hidden;
        cursor: pointer;

        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s;
        }

        &:hover img {
            transform: scale(1.05);
        }
    }

    .content {
        padding: 24px;

        .title {
            font-size: 20px;
            font-weight: 600;
            color: #2F3B59;
            margin-bottom: 8px;
            cursor: pointer;
            
            &:hover {
                color: #4A60A1;
            }
        }

        .community {
            font-size: 14px;
            color: #6D737A;
            margin-bottom: 16px;
        }

        .house-info {
            display: flex;
            gap: 24px;
            margin-bottom: 24px;
            color: #2F3B59;

            .info-item {
                font-size: 14px;
            }
        }

        .price {
            margin-bottom: 16px;
            
            .amount {
                font-size: 20px;
                font-weight: 600;
                color: #4A60A1;
            }
        }

        .bottom {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-top: 16px;
            border-top: 1px solid #EDEFF6;

            .agent {
                display: flex;
                align-items: center;
                gap: 8px;

                .agent-avatar {
                    width: 32px;
                    height: 32px;
                    border-radius: 50%;
                    object-fit: cover;
                }

                .agent-name {
                    font-size: 14px;
                    color: #2F3B59;
                }
            }

            .actions {
                display: flex;
                gap: 8px;

                .action-btn {
                    width: 30px;
                    height: 30px;
                    border: none;
                    background: #EDEFF6;
                    border-radius: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    cursor: pointer;
                    transition: all 0.3s;

                    .svg-icon {
                        width: 22px;
                        height: 22px;
                        color: #4A60A1;
                    }

                    &:hover {
                        background: var(--light-hover);
                    }
                }
            }
        }
    }

    .collect-btn {
        position: absolute;
        top: 10px;
        right: 10px;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 2;
        transition: all 0.3s;
        
        &:hover {
            background: #fff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .collect-icon {
            font-size: 18px;
            color: #909399;
            
            &.active {
                color: #F56C6C;
            }
        }
    }
}
</style> 